<?php

/**
 * @author Pwint Phyu Shwe
 * Profile Controller
 *
 * Maps to the following url
 * http://domain/index.php/profile
 * or
 * http://domain/index.php/profile/index
 */

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Profile extends CI_Controller {

	// num of records per page
	private $limit = 10;

	function __construct() {
		parent::__construct();

		// load library
		$this->load->library(array('form_validation'));
		// load helper
		$this->load->helper(array('url', 'form', 'html','login','common'));
		// load model
		$this->load->model('User_model','',TRUE);
		
	}


	function index($offset = 0){
		// load view
		$data['title'] = 'My Account Management';
		$data['message'] = '';
		//$data['action'] = site_url('profile/update');
		// load view
		$this->load->view('dashboard_view', $data);
	}

	//display registration page
	function registration(){
		
		// set common properties
		$data['title'] = 'Member Registration';
		$data['message'] = '';
		$data['action'] = site_url('admin/profile/add');
		
		// load view
		$this->load->view('signup_view', $data);
	}
	// register user
	function add(){
		// set common properties
		$data['title'] = 'Member Registration';
		
		// set form_validation properties
		//$this->_set_rules();

		// run form_validation
		if ($this->form_validation->run('signup') == FALSE){
			$data['message'] = 'Validation failed';
			$data['action'] = site_url('admin/profile/add');
			$this->load->view('signup_view', $data);
			
		}else{
			// save data
			$password = $this->input->post('password');
			$user = array('firstName' => $this->input->post('name'),
					'displayName' =>$this->input->post('displayname'),
					'phone' => $this->input->post('contactno'),
					'address' => $this->input->post('address'),
					'city' => $this->input->post('city'),
					'country' => $this->input->post('country'),
					'emailAddress' => $this->input->post('email'),
					'password' =>MD5($password));

			//do upload
			//if (is_uploaded_file($_FILES['userfile']['tmp_name'])){
			if (isset($_FILES['userfile']['tmp_name']) && !empty($_FILES['userfile']['tmp_name'])) {
				$image_url = upload_file();
				if($image_url){
					$urls = array_values($image_url);
					$user['image_url'] = isset($urls[0]) ? $urls[0] : null;;
					}else{
						$data = array('message' => $this->upload->display_errors(), 'action' => 'admin/profile/add');
						$this->load->view('signup_view', $data);
					}
			}
			$id = $this->User_model->save($user);
			if ($id){
				
					$info = $this->set_login($user['emailAddress'], $password);
					if (! $info)
					{
						$data = array('message' => $info. $user['emailAddress']. $user['password'], 'action' => 'admin/profile/add');
						$this->load->view('signup_view', $data);
					}else{
						$this->form_validation->id = $id;
						// set user message
						$data['message'] = '<div class="success">Congruations! Welcome to MayKha Family. You can start enjoying free advertisement anything from accessories to property. If anything please contact administrator@maykhaclassifieds.com' . $info . '</div>';
						// load view
						$this->load->view('/admin/dashboard_view', $data);
					}
					//$this->load->model('Credit_model','',TRUE);
					//$result = $this->Credit_model->add($id,100);
			}
				
		}
	}

	function view($id){
		// set common properties
		$data['title'] = 'Profile';
		$person = $this->personModel->get_by_id($id);

		// get person details
		$data['person'] = $person;
		// load view
		$this->load->view('personView', $data);
	}

	function update($id , $message=NULL){
		// prefill form values
		$person = $this->User_model->get_by_id($id);
		if($message!=NULL)
			$data['message'] =  urldecode ( $message );
		// set common properties
		$data['user'] = $person;
		$data['title'] = 'Change Profile';
		$data['action'] = site_url('admin/profile/updateUser');
				// load view
		$this->load->view('pages/profile', $data);
	}

	function updateUser(){
		// set common properties
		$data['title'] = 'Update person';
		$data['action'] = site_url('admin/profile/updateUser');
		$data['message'] = '<div class="success">update person success</div>';
		
		$this->form_validation->set_rules('name', 'name', 'required');
		$this->form_validation->set_rules('phone', 'phone', 'required');
		
		// run form_validation
		if ($this->form_validation->run() == FALSE){
			$data['message'] = 'Error in the form';
			$this->update($this->input->post('id'), 'Error in Form=>');
		}else{
			// save data
			//'dob' => date('Y-m-d', strtotime($this->input->post('dob'))));
			$id = $this->input->post('id');
			$person = array(
					'firstname' => $this->input->post('name'),
					'displayName' => $this->input->post('displayName'),
					'phone' => $this->input->post('phone'),
					'address' => $this->input->post('address')
					);
					
			if($this->input->post('inputPassword') && $this->input->post('newPassword')){
				 if (MD5($this->input->post('inputPassword')) == $this->input->post('oldpsw')){
					$person['password'] = MD5($this->input->post('newPassword'));
				 }else{
					redirect('/admin/profile/update/' . $this->input->post('id') . '/'. 'Old password does not match with existing' , 'refresh');
				 }
			}
			$this->User_model->update($id,$person);
			// load view
			$this->update($id, 'Information is updated successfully');
			
		}

		
	}

	function delete($id){
		// delete person
		$this->personModel->delete($id);

		// redirect to person list page
		redirect('person/index/','refresh');
	}
	//jquery test !!! not using !!!
	function emailexists()
	{
		if (array_key_exists('email',$_POST)) {
			if ( $this->User_model->email_exists($this->input->post('email')) == TRUE ) {
			  echo json_encode(FALSE);
			} else {
			  echo json_encode(TRUE);
			}
		}
	}
	//validation checked for email
	function email_exists()
	{	if ( $this->User_model->email_exists($this->input->post('email')) == TRUE ) {
			$this->form_validation->set_message('email_exists', '<span class="error"> %s  has already registered. Login using this account</span>');
			  return false;
		} else {
			  return true;
		}
	}
	// date_validation callback
	function valid_date($str)
	{
		if(!ereg("^(0[1-9]|1[0-9]|2[0-9]|3[01])-(0[1-9]|1[012])-([0-9]{4})$", $str))
		{
			$this->form_validation->set_message('valid_date', 'date format is not valid. dd-mm-yyyy');
			return false;
		}
		else
		{
			return true;
		}
	}
	//password validation callback
	function password_check($str)
	{
		if (preg_match('#[0-9]#', $str) && preg_match('#[a-zA-Z]#', $str)) {

			return TRUE;
		}
		$this->form_validation->set_message('password_check', 'Password must contain at least 8 characters with alphanumeric');
		return FALSE;
	}
	
	/**
	 * Logout and unset session log in data
	 */
	function logout() {
		$sess_array = array(
				'userid' => '',
				'email' => '',
				'name' => '',
				'is_logged_in' => ''
		);
		$this->session->unset_userdata($sess_array);
		redirect('home', 'refresh');

	}
	/**
	 * Login
	 * @param unknown_type $isRegistered
	 * login view
	 */
	function login() {
		$data['action'] = site_url('admin/profile/dologin');;
		$data['title'] = 'Member Login';
		$data['message'] = 'Please login using email and password to view admin panel';
		$this->load->view('login_view', $data);
	}
	function dologin(){
		
		if($this->form_validation->run('login') == FALSE)
		{
			//Field validation failed.  User redirected to login page
			$data['action'] = site_url('admin/profile/dologin');;
			$data['title'] = 'Member Login';
			$this->load->view('login_view', $data);
		}
		else
		{
			
			//Go to private area
			if ($this->session->userdata('redirectUrl'))
				redirect($this->session->userdata['redirectUrl']);
			else{
				redirect('admin/dashboard');
			}
		}
	}

	function check_database($password)
	{
		//Field validation succeeded.  Validate against database
		$username = $this->input->post('username');
		$result = $this->set_login($username, $password);
		return $result;
	}
	function set_login($username, $password)
	{
		//query the database
		$result = $this->User_model->login($username, $password);

		if($result)
		{
			$sess_array = array();
			foreach($result as $row)
			{
				if (isset($row->activationCode)){
					$this->form_validation->set_message('check_database', 'account has not been activated');
					return false;
				}
				$sess_array = array(
						'is_logged_in' => true,
						'userid' => $row->userID,
						'email' => $row->emailAddress,
						'name' => $row->firstName . ' ' . $row->lastName
				);
				
				$this->session->set_userdata($sess_array);
				//generateRedirectURL();
			}
			return TRUE;
		}
		else
		{
			$this->form_validation->set_message('check_database', 'Invalid username or password');
			return false;
		}
	}
	/**
	 * [reset description]
	 * @return [type] [description]
	 */
	function reset(){
		$data['title'] = 'Forgot password';
		$data['action'] = site_url('admin/profile/forgot');
		$this->load->view('/forms/changepassword', $data);
	}
	/**
	 *  Call from Reset Password Form, Send new password to user
	 * @return [type] [description]
	 */
	function forgot(){
		 if ( $this->input->post('email')) {
		 	if ($this->form_validation->run('resetfrm') == FALSE)
			{
				$data['message'] = 'Validation failed';
				$data['action'] = site_url('admin/profile/forgot');
				$this->load->view('/forms/changepassword', $data['message']);
			}else{
		 	 $emailid =  $this->input->post('email');
		 	 	if (! $this->email_exists($emailid)) {
					 $this->load->helper('string');
					 $password = random_string('alnum', 10);
					 $user['password'] = MD5($password);
			         $cond['emailAddress'] = $emailid;
			         $this->User_model->update($cond, $user);
			         $message = '<br /><h2>Your Password Has Been Reset</h2> <br />'
			        			. '<p>Your new Password is </p><br />'
			        			. $password;
			         $messageParam['to'] =  $emailid;
					 $messageParam['from'] = $this->config->item('email');
					 $messageParam['subject'] = '[Maykhaclassifieds.com]: Reset Password';
					 $messageParam['messagebody'] = $message;
					 $messageParam['replyTo'] = 'info@maykhaclassifieds.com';
					 $messageParam['url'] = 'www.maykhaclassifieds.com';
			         $this->load->helper('aws_email');
		             send_email_via_aws($messageParam);
		             $data['header'] = $emailid;
		             $data['currenturl'] = 'Reset Email';
		             $data['description']  = 'Your password has been sent to the email address registered to your account.
												If you do not receive the message shortly:
												<ul>
												<li>Your account may be disabled.</li>
												<li>Your account email address may be set differently from that expected.</li>
												<li>An account may not exist for this email address Create an Account</li></ul>';
		             $this->load->view('/pages/success', $data);
		         }else{
		         	$data['message'] = 'The Email address you entered cannot find in the system. Please re-type again. 
		         	If you think the account does not have. <a href="'. base_url('/registration'). '">Create an Account</a><br /><br />';
		         	$data['action'] = site_url('admin/profile/forgot');
					$this->load->view('/forms/changepassword', $data);
		         }
             }
         }


	}

}
?>